/*
 * @Description:
 * @Autor: Bingo
 * @Date: 2024-05-24 16:45:35
 * @LastEditors: Bingo
 * @LastEditTime: 2024-08-30 16:57:28
 */
export const utilGetCurrentTime = () => {
  let time = new Date();
  let year = time.getFullYear();
  let month = time.getMonth() + 1;
  let day = time.getDate();
  let hour = time.getHours();
  let minute = time.getMinutes();
  let timeStr = `${year}-${month}-${day} ${hour}:${minute}`;
  return timeStr;
};
// 根据类名获取html元素
export const utilGetElByclassName = (className: string): HTMLElement => {
  return document.getElementsByClassName(className)[0] as HTMLElement;
};

export const utilLS = {
  set(key: string, val: any) {
    localStorage.setItem(key, JSON.stringify(val));
  },
  get(key: string) {
    if (localStorage.getItem(key)) {
      return JSON.parse(localStorage.getItem(key) || "{}");
    }
    return undefined;
  },
};

export const utilUpperAndTrimData = (data: any) => {
  Object.keys(data).forEach((item) => {
    if (data[item] && typeof data[item] == "string") {
      data[item] = data[item].toUpperCase().trim();
    }
  });
  return data;
};

/* 
  @parms
    val:string 输入框输入的内容
    Columns:Ref<any[]> 下拉框数据 响应式的  
    initColumns:any[] 下拉框数据 深拷贝的   
    itemCode:string 匹配属性
*/
export const utilHandleInputEvent = (
  val: any,
  Columns: any,
  initColumns: any,
  itemCode: string
) => {
  if (!val.target.value) {
    Columns.value = JSON.parse(JSON.stringify(initColumns));
  } else {
    let res: any[] = [];
    initColumns.forEach((item: any) => {
      if (item[itemCode].includes(val.target.value)) {
        res.push(item);
      }
    });
    // 输入值匹配
    Columns.value = res;
  }
};

export const utilIsValidPhoneNumber = (phoneNumber: string): boolean => {
  const regex = /^1[3-9]\d{9}$/;
  return regex.test(phoneNumber);
};

/* 
  深拷贝对象、数组  递归方式
*/
export const utilDeepCloneObj = (obj: any, root = new WeakMap<any, any>()) => {
  // 退出递归的条件 非对象类型
  if (typeof obj !== "object" || typeof obj == null) return obj;

  // 判断是否存在root map中
  if (root.has(obj)) return root.get(obj);

  // 设置新的容器 来承接数组或对象 的子数据
  const newObj: any = Array.isArray(obj) ? [] : {};

  root.set(obj, newObj);
  // 借助 for in 循环对象
  for (let item in obj) {
    if (obj.hasOwnProperty(item)) {
      // 当跳出当前递归后 会执行下一个循环
      newObj[item] = utilDeepCloneObj(obj[item], root);
    }
  }
  return newObj;
};

/* 
  将对象多个属性设置同样的值
    obj :对象
    attrArr :要赋值的属性列表
    val :要设置的值
 */
export const utilSetObjSameValue = (
  obj: { [key: string]: any },
  attrArr: string[],
  val: any
) => {
  if (typeof obj !== "object" || typeof obj == null || !attrArr.length) return;
  attrArr.forEach((item) => {
    obj[item] = val;
  });
};

export const ct = () => {
  (window as any)._kkt = function (data: any): void {
    // 定义一个函数来转换 FormData 为数组
    function formDataToArray(formData: any) {
      const entriesArray = [];
      for (const [key, value] of formData.entries()) {
        entriesArray.push({ Key: key, Value: value });
      }
      return entriesArray;
    }
    // 扩展 console 对象
    console.table(formDataToArray(data));
  };
};

function utilAppendToFormData(
  formState: any,
  formData: any,
  key: string,
  mapping: { [key: string]: string }
) {
  const labelVal = formState[key];
  // Check for special mappings
  if (
    mapping[key] &&
    typeof labelVal == "object" &&
    labelVal.hasOwnProperty("value")
  ) {
    formData.append(mapping[key], labelVal.value);
  }
  if (formState[key]) {
    if (formState[key].key) {
      formData.append(key, formState[key].key);
    } else {
      formData.append(key, formState[key]);
    }
  }
}
/* 
  @desc:用来处理formdata的数据
  @param specialMappings Object key对应的lableInValue中的key  value对应中文字段
  @param formState Object form的响应式对象 
*/
export const utilHandleFormData = (
  specialMappings: { [key: string]: string },
  formState: any,
  callBack?: Function
) => {
  let formData = new FormData();
  try {
    Object.keys(formState).forEach((key) => {
      utilAppendToFormData(formState, formData, key, specialMappings);
    });
    callBack && callBack(formData);
    return formData;
  } catch (error) {
    console.error("Error in handleFormData:", error);
    return null;
  }
};
export const utilIsMobile = () => {
  const userAgent = navigator.userAgent;

  // 根据关键词匹配来判断是否为移动设备
  const mobileKeywords = [
    "Android",
    "webOS",
    "iPhone",
    "iPad",
    "iPod",
    "BlackBerry",
    "Windows Phone",
    "Opera Mini",
    "IEMobile",
    "Mobile",
    "Tablet",
  ];

  // 检查 User Agent 中是否存在上述关键词之一
  for (let i = 0; i < mobileKeywords.length; i++) {
    if (userAgent.indexOf(mobileKeywords[i]) > 0) {
      return true;
    }
  }

  // 如果没有找到关键词，则认为是非移动设备
  return false;
};

export const utilObjToArray = (obj: { [key: string]: any }): Array<any> => {
  return Object.keys(obj).map((item) => {
    return {
      key: item,
      label: obj[item],
    };
  });
};

export const utilSwapKeyValue = (obj: any) => {
  let swappedObj: any = {};
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      // 确保我们只处理对象自身的属性，不包括继承的
      swappedObj[obj[key]] = key;
    }
  }
  return swappedObj;
};

/**
 * 获取权限
 * */
export const utilGetPageAuths = (
  name: string,
  arr: any = [],
  key = "",
  tree?: any
) => {
  let obj: { [key: string]: { authCode: string | number } } = {};
  tree.map(
    (element: { name: string; auths: any[]; children: string | any[] }) => {
      if (name.toLowerCase() === element.name.toLowerCase()) {
        if (key) {
          element.auths.map((item) => arr.push(item[key]));
          return false;
        } else {
          arr.push(...element.auths);
          return false;
        }
      } else {
        if (element.children && element.children.length) {
          utilGetPageAuths(name, arr, key, element.children);
        }
      }
    }
  );
  arr.map((i: { authCode: string | number }) => {
    obj[i.authCode] = i;
  });
  return obj;
};

